<template>
    <view class="flex h-full">
        <left-aside></left-aside>

        <view class="mt-[20rpx] w-full">
            <z-paging
                ref="paging"
                v-model="goodsList"
                @query="getData"
                :fixed="false"
                height="100%"
                :auto-clean-list-when-reload="false"
                :auto-scroll-to-top-when-reload="false"
            >
                <view class="mx-[20rpx]">
                    <l-swiper
                        class="mb-[20rpx]"
                        height="200"
                        v-if="page.enabled"
                        :content="page"
                        mode="none"
                    />
                    <view>
                        <sort-nav v-if="webType!=2" v-model:active="sort" @change="changeNav"></sort-nav>

                        <view class="mt-[20rpx]" v-for="item in goodsList" :key="item.id">
                            <!-- <router-navigate
                                :to="`/pages/goods_detail/goods_detail?id=${item.id}`"
                                open-type="navigate"
                                hover-class="none"
                            > -->
                                <goods-card
                                    shape="rectangle"
                                    :name="item.name"
                                    :image="item.image"
									:jumpUrl = "`/pages/goods_detail/goods_detail?id=${item.id}`"
                                >
                                    <view class="mt-2">
                                        <view class="mb-2 text-muted" v-if="webType!=2 && item.lineationPrice > 0">
                                            原价¥{{ item.lineationPrice }}
                                        </view>
										<view class="text-muted mb-[10rpx]" v-if="webType==2">
											<view class="sales-num font20">已售{{ item.salesNum }}</view>										    
										</view>
										<view class="item-row-between" style="width: 280rpx;">
											<view class="item-row">
												<price
												    :content="item?.price"
												    main-size="32rpx"
												    minor-size="24rpx"
												    fontWeight="500"
												/>
												<span v-if="webType==2" class="ml-[10rpx] text-muted line-through font24">¥{{item?.lineationPrice}}</span>
											</view>
											
											<view v-if="webType==1 && item?.specValueList.length==1" class="item-row">
												<span v-if="getCartNum(item.id)>0" :style="{ background: color }" class="item-row-center buy-num" @click="buttonsHandle(0,item)">-</span>
												<span v-if="getCartNum(item.id)>0" class="ml-[10rpx] mr-[10rpx]">{{getCartNum(item.id)}}</span>
												<span :style="{ background: color }" class="item-row-center buy-num" @click="buttonsHandle(1,item)">+</span>
											</view>	
											
											<view v-else-if="webType==1 && item?.specValueList.length>1" class="item-row">
												<span :style="{ background: color }" class="item-row-center buy-guige" @click="buttonsGeHandle($event,item)">选规格</span>
											</view>
											
											<view v-else-if="webType==2" class="item-row">											
												<span :style="{ background: color }" class="item-row-center jiaz-buy font24" @click="goDetail(item)">购买</span>									
											</view>
											
										</view>
                                    </view>
                                </goods-card>
                            <!-- </router-navigate> -->
                        </view>
                    </view>
                </view>
            </z-paging>	
			
			<!-- 规格打开 -->
			<GoodsSpec
			    ref="goodsSpecRef"
			    :defaultInfo="{
			        image: goods.goodsImage[0],
			        price: goods.sellPrice,
			        stock: goods.totalStock,
			        unit: goods.unit_name
			    }"
			    :buttons="goods.buttons"
			    :spec-list="goods.specValue"
			    :spec-map="goods.specValueList"
			    :activity-spec="activity.goodsSku"
			    priceKey="price"
			    @change="changeGoodsSpec"
			    @buttonsHandle="buttonsSubmitHandle"
			/>	
			<!-- 悬挂购物车 -->			
			<view v-if="webType==1" class="footer">
				<view class="item-row-between position-footer">
					<view class="item-row mt-[-40rpx]">					
						<span @click.stop="openCart" class="cart-bg item-row-center">
							<image class="cart-img" src="/static/images/icon/cart.png" />
						</span>
						<span :style="{ background: color }" class="cart-num item-row-center">{{cart.goods.length}}</span>
						<span class="mt-[40rpx]">
							¥
							<span class="text-lg">{{cart.totalPrice}}</span>
						</span>
					</view>
					<view @tap="goToConfirm" :style="{ background: color }" class="item-row-center go-pay">去结算</view>
				</view>				
			</view>
			
			<!-- 购物车打开 -->
			<u-popup							
				v-model="showCoupon"
				style="position: absolute;bottom:200rpx;background: #FFF;z-index: 999;"
				mode="bottom"				
				:duration="50"
				border-radius="14"
				:closeable="false"			
				:safeAreaInsetBottom="true"
			>
				<view class="coupons mb-[30rpx]">
					<view class="coupons-header p-[30rpx] flex justify-between">
						<!-- text-[#101010] -->
						<!-- <u-icon name="close" color="#666666" @tap="showCoupon = false" /> -->
						<span></span>
						<span @click="handleDel">
							<u-icon name="trash" color="#666666" />
							<!-- <text class="text-[#666666] text-lg">清空</text> -->
						</span>			            
					</view>
					<view class="coupons-main">
						<scroll-view :scroll-y="true" style="height: 700rpx; touch-action: none">
							<view v-if="cart.goods.length>0" v-for="item in cart.goods" :key="item.id">
								<goods-card
									shape="rectangle"
									:name="item.name"
									:image="item.image"
									:jumpUrl = "`/pages/goods_detail/goods_detail?id=${item.id}`"
								>								
									<view v-if="webType==1" class="cart-guige">
										<span class="text-[#666666] mr-[6rpx] text-xs">{{item?.skuValueArr.replaceAll(",",' ')}}</span>
										<!-- <u-icon name="arrow-down" size="18" color="#666666" /> -->
									</view>	
								
									<view class="mt-2">			
										<view class="item-row-between" style="width: 460rpx;">
											<price
												:content="item?.price"
												main-size="32rpx"
												minor-size="24rpx"
												fontWeight="500"
											/>											
											<view v-if="webType==1" class="item-row">
												<span v-if="item?.num>0" :style="{ background: color }" class="item-row-center buy-num" @click="buttonCartHandle(0,item)">-</span>
												<span v-if="item?.num>0" class="ml-[10rpx] mr-[10rpx]" >{{item?.num}}</span>
												<span :style="{ background: color }" class="item-row-center buy-num" @click="buttonCartHandle(1,item)">+</span>
											</view>											
										</view>
									</view>
								</goods-card>
							</view>	
												
							<view
							    class="text-center mb-[20rpx]"
							    style="padding: 80rpx 0 50rpx"
							    v-show="isLogin && cart.goods.length == 0"
							>
							    <image
							        class="w-[300rpx]"
							        src="/static/images/empty/shopping_cart.png"
							        mode="widthFix"
							    ></image>
							    <!-- <view class="text-[#999] mb-[30rpx]">购物车空空如也~</view> -->							    
							</view>
						</scroll-view>
					</view>
				</view>
			</u-popup>	
			
				
				
        </view>		
    </view>	
</template>

<script lang="ts" setup>
import leftAside from './left-aside.vue';
import { getGoodsLists, shoppingCartLists, shoppingCartDel, shoppingCartSelect, getGoodsDetail, shoppingCartChange } from "@/api/goods"
import { useDataEffect } from "./useDataEffect";
import { useSubmitEffect } from '@/pages/goods_detail/useSubmitEffect'
import { reactive, nextTick, ref, watch, shallowRef } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { useUserStore } from '@/stores/user'
import { useRouter } from 'uniapp-router-next'
import GoodsSpec from '@/components/goods-spec/goods-spec.vue'
import { storeToRefs } from 'pinia'
import { useAppStore } from '@/stores/app'
const appStore = useAppStore()
const webType = appStore.getWebType

const userStore = useUserStore()
const { isLogin } = storeToRefs(userStore)
const router = useRouter()
const { list, page, current } = useDataEffect()

const paging = shallowRef()
const goodsList = ref<any>([])
const sort = ref<string>('');
const showCoupon = ref<boolean>(false)

const { getShopCartCount } = useUserStore()

// 多规格
const goodsSpecRef = shallowRef()

const goods = ref<any>({
    id: -1,
    // 顶部导航栏
    percent: '',
    // 返回顶部按钮的当前滚动条数值
    scrollTo: 0,
    // 轮播图
    goodsImage: [],
    // 已选择的商品sku
    checkedSku: {},
    // 配送区域
    defaultAddress: {
        addressId: 0,
        provinceName: '北京',
        cityName: '北京市',
        districtName: '朝阳区'
    },
    // 配送费
    defaultFreight: 0,
    // 是否收藏
    isCollect: 0,
    // 当前选中的底部按钮
    buttons: [],
    // 底部提交按钮组
    buttonsGroup: {},
    // 商品所属分类
    categoryId: [],
    // 装修数据
    decorate: [],
    // 评论数据
    goodsComment: [],
    // 猜你喜欢列表
    goods_like: [],
    //佣金
    earningsData: {}
})

// 活动
const activity = ref<any>({
    goodsId: '',
    startTime: '',
    minSeckillPrice: '',
    goodsSku: [],
    checkedSku: {},
    browseVolume: '',
    salesVolume: ''
})

const props = withDefaults(
    defineProps<{
        content: string | number // 标题
        prec?: number // 小数数量
        autoPrec?: boolean // 动态小数
        color?: string // 颜色
        mainSize?: string // 主要内容字体大小
        minorSize?: string // 次要内容字体大小
        lineThrough?: boolean // 贯穿线
        fontWeight?: string // 字重
        prefix?: string // 前缀
        suffix?: string // 后缀
    }>(),
    {
        content: '',
        prec: 2,
        autoPrec: true,
        // color: '#FF2C3C',
        color: 'var(--theme-color)',
        mainSize: '36rpx',
        minorSize: '28rpx',
        lineThrough: false,
        fontWeight: 'normal',
        prefix: '￥',
        suffix: ''
    }
)

type ShoppingCartItem = {
    cartStatus: number
    goods: any
    goodsId: number
    goodsSkuId: number
    price: string
    id: number
    num: number
    selected: number
    sku: any
    show?: boolean
}

type ShoppingCartParam = {
    loading: boolean
    goods: ShoppingCartItem[]
    hot_lists: any[]
    totalNum: number
    totalPrice: number
    showDelTips: boolean
}

const cart = reactive<ShoppingCartParam>({
    loading: true,
    goods: [],
    hot_lists: [],
    totalNum: 0,
    totalPrice: 0,
    showDelTips: false
})

const getCartNum = (id:number) =>{
	const num = cart.goods.filter((item) => item.goodsId ==id).map((item) => item.num)
	return num[0];
}

const changeNav = () => {
    paging.value.reload()
}

// 购买
const goDetail = (item: any) => {
	uni.navigateTo({
		url: '/pages/goods_detail/goods_detail?id='+item.id
	})
}

const openCart = () => {
	//console.log("isLogin:"+isLogin.value)
	if(isLogin.value==false){
		uni.navigateTo({
			url: '/pages/login/login'
		})
	}	
	showCoupon.value = !showCoupon.value
}

// 改变购物车数量
const buttonCartHandle = async (type: number,options: any) => {	
	const params = {id:options.id,num:0};		
	if(type==1){		
		params.num = options.num+1;
	}else{
		params.num = options.num-1;
	}			
	await shoppingCartChange(params)
	await getShoppingCart()
	await handleAllSelect()
	if(cart.goods.length==0){
		showCoupon.value = false;
	}
}

// 添加购物车 单规格
const buttonsHandle = async (type: number,options: any) => {	
	if(type==1){		
		options.number = 1;
	}else{
		options.number = -1;
	}	
	const { cartHandle } = useSubmitEffect()
	console.log("options"+JSON.stringify(options))
	let params = {spec:options}	
	await cartHandle(params)
	await getShoppingCart()
	await handleAllSelect()
}

// 选规格
const buttonsGeHandle = async ($event: any,options: any) => {	
	const data = await getGoodsDetail({ id: options.id })	
	goods.value = data
	console.log("goods:" + JSON.stringify(goods.value))
	//showGeCoupon.value = true;	
	goods.value.checkedSku = {}
	goodsSpecRef.value?.handleOpen({ ...$event })	
	goods.value.buttons = [{ text: '选好了', style: {}, event: 'buy' }]
}

// 添加到购物车
const buttonsSubmitHandle = async () => {	
	const options = activity.value.checkedSku;
	const { cartHandle } = useSubmitEffect()
	console.log("options"+JSON.stringify(options))
	let params = {spec:options}	
	await cartHandle(params)
	await getShoppingCart()
	await handleAllSelect()
}

// 改变规格
const changeGoodsSpec = (options: any) => {
	activity.value = {}
    console.log(options)
    goods.value.checkedSku = options.spec
    activity.value.checkedSku = options.spec
	console.log("checkedSku:"+JSON.stringify(goods.value))
}

// 去结算
const goToConfirm = () => {
    const buyGoods = cart.goods
        .filter((item: ShoppingCartItem) => item.selected)
        .map((item: ShoppingCartItem) => {
            return {
                cartId: item.id,
                num: item.num,
                skuId: item.goodsSkuId,
                goodsId: item.goodsId
            }
        })
	if(cart.goods.length<=0){
		return uni.$u.toast('请选择商品')	
	}
    router.navigateTo({
        path: '/pages/goods_order/goods_order',
        query: {
            buyGoods: JSON.stringify(buyGoods),
            buyType: 'cart'
        }
    })
}

const getData = async (pageNo: number, pageSize: number) => {	
    try {
        const { lists } = await getGoodsLists({
            pageNo: pageNo,
            sort: sort.value,
            pageSize: pageSize,
            categoryId: list.value[current.value].id
        })
        paging.value.complete(lists)
    } catch (error) {
        console.log(error)
        paging.value.complete(false)
    }
}

watch(
    () => current,
    (val) => {
        sort.value = '';
        paging.value.reload()
        console.log(val.value)
    },
    {
        deep: true
    }
)

// 全选操作
const handleAllSelect = async () => {
    try {
        const ids = cart.goods.filter((item) => !item.cartStatus).map((item) => item.id)
        await shoppingCartSelect({ ids: ids, isSelected: 1 })
        // 改变后重新获取购物车
        await getShoppingCart()
    } catch (error) {
        console.log('全选', error)
    }
}

const getShoppingCart = async () => {
    try {
        const { goods, totalPrice, totalNum }: ShoppingCartParam = await shoppingCartLists()
        goods.forEach((item: ShoppingCartItem) => {
            item.show = false
        })
        cart.goods = goods
        cart.totalNum = totalNum
        cart.totalPrice = totalPrice
    } catch (error) {
        console.log('获取购物车列表失败', error)
    }
    await nextTick()
    cart.loading = false
}

const handleDel = async () => {
    try {
        const ids: number[] = cart.goods
            .filter((item) => !item.cartStatus && item.selected)
            .map((item) => item.id)
        await shoppingCartDel({ ids: ids })
        // 改变后重新获取购物车
        await getShoppingCart()
        //
        await getShopCartCount()
		showCoupon.value = false
    } catch (error) {
        console.log('全选', error)
    }
}

onShow(() => {
    getShoppingCart()
    //getShopCartCount()	
})
</script>